package com.coder.bike.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.bike.entity.Customer;
import com.coder.bike.security.CustomerUserDetailsService;
import com.coder.bike.service.ICustomerService;
import com.coder.bike.utils.LoginUtil;
import com.coder.bike.utils.RedisUtils;
import com.coder.bike.utils.Result;
import com.coder.bike.vo.CustomerRegisterDTO;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

import static com.coder.bike.utils.LoginUtil.authenticateUser;
import static com.coder.bike.utils.LoginUtil.verifySmsCode;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 沈诩宸
 * @since 2025-04-22
 */
@RestController
@RequestMapping("/bike/customer")
public class CustomerController {
    @Resource
    private ICustomerService iCustomerService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private CustomerUserDetailsService customerUserDetailsService;

    @GetMapping
    public Result getAllCustomers() {
        return Result.success(iCustomerService.list());
    }

    @PostMapping("{start}/{size}")
    public Result search(@PathVariable int start, @PathVariable int size,
                         @RequestBody Customer customer) {
        return Result.success(iCustomerService.searchByPage(new Page<>(start, size), customer));
    }

    @PostMapping
    public Result save(@RequestBody Customer customer) {
        Customer existingCustomer = iCustomerService.selectByUsername(customer.getUsername());
        if (existingCustomer != null) {
            return Result.fail().setMessage("用户名已存在");
        } else {
            customer.setStatus(true); // 默认设置为白名单
            customer.setIsVerified(false); // 默认未认证
            customer.setCreditScore(100); // 默认信誉积分
            if (customer.getAvatar() == null || customer.getAvatar().isEmpty()) {
                customer.setAvatar("http://gips1.baidu.com/it/u=1410005327,4082018016&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280");
            }
            return iCustomerService.save(customer) ? Result.success() : Result.fail();
        }
    }

    @PutMapping
    public Result update(@RequestBody Customer customer) {
        Customer existingCustomer = iCustomerService.selectByUsername(customer.getUsername());
        if (existingCustomer != null && !Objects.equals(existingCustomer.getId(), customer.getId())) {
            return Result.fail().setMessage("用户名已存在");
        }
        return iCustomerService.updateById(customer) ? Result.success() : Result.fail();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return iCustomerService.removeById(id) ? Result.success() : Result.fail();
    }

    @GetMapping("getIdByName/{realName}")
    public Result getIdByName(@PathVariable String realName) {
        Customer customer = iCustomerService.selectByName(realName);
        if (customer != null) {
            return Result.success(customer.getId());
        } else {
            return Result.fail().setMessage("用户找不到");
        }
    }

    @GetMapping("getNameById/{id}")
    public Result getNameById(@PathVariable Integer id) {
        Customer customer = iCustomerService.getById(id);
        if (customer != null) {
            return Result.success(customer.getName());
        } else {
            return Result.fail().setMessage("不存在此用户");
        }
    }
    @GetMapping("getById/{id}")
    public Result getById(@PathVariable Integer id) {
        try {
            Customer customer = iCustomerService.getById(id);
            if (customer != null) {
                return Result.success(customer);
            } else {
                return Result.fail().setMessage("不存在此用户");
            }
        } catch (Exception e) {
            return Result.fail().setMessage("获取用户信息失败: " + e.getMessage());
        }
    }
    @PostMapping("registerByPhone")
    public Result registerByPhone(@RequestBody CustomerRegisterDTO dto) {
        // 验证短信验证码
        Result verifyResult = verifySmsCode(redisUtils, dto.getPhone(), "register", dto.getCode());
        if (!verifyResult.getSuccess()) {
            return verifyResult;
        }
        // 检查手机号是否已注册
        Customer existingCustomer = iCustomerService.selectByPhone(dto.getPhone());
        if (existingCustomer != null) {
            return Result.fail().setMessage("该手机号已注册");
        }
        Customer customer = getCustomer(dto);
        if (iCustomerService.save(customer)) {
            return  Result.success();
        }
        return Result.fail();
    }

    private static Customer getCustomer(CustomerRegisterDTO dto) {
        Customer customer = new Customer();
        customer.setTel(dto.getPhone());
        customer.setUsername(dto.getPhone());
        customer.setPassword(dto.getPassword());
        customer.setName(dto.getName() != null ? dto.getName() : "用户" + dto.getPhone().substring(7));
        customer.setStatus(true);
        customer.setIsVerified(false);
        customer.setCreditScore(100);
        if (dto.getAvatar() == null || dto.getAvatar().isEmpty()) {
            customer.setAvatar("http://gips1.baidu.com/it/u=1410005327,4082018016&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280");
        } else {
            customer.setAvatar(dto.getAvatar());
        }
        return customer;
    }


}